def selection = (textArea.selection?.size() > 0)?textArea.selection[0].clone():null

def logic = { text ->
    text.readLines().findAll{ it.trim().size() }.join("\n") + "\n"
}

if( textArea.selectedText ){
    textArea.selectedText = logic(textArea.selectedText)
} else {
    textArea.text = logic(textArea.text)
}
textArea.addToSelection(selection)

